<template>
  <div class="app-container">
<!--     顶部搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="originalFileName">
        <el-input
          v-model="queryParams.originalFileName"
          placeholder="请输入文件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择文件类型" clearable size="small">
          <el-option
            v-for="dict in contentTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>
<!--    文件路径 与 汇总信息 -->
    <el-row type="flex" class="row-bg" justify="space-around">
      <el-col :span="6"><div class="grid-content bg-purple">
        <el-link  type="primary line-height:1.7 font-weight:bold" v-for="(item, index) in directoryList" v-bind:key="item.name"  @click.native="handleLink(item)">{{item.name}}</el-link>
      </div></el-col>
      <el-col :span="6"><div class="grid-content bg-purple-light">
        <span>桶内对象数量： {{fileTotalInfo.totalFileInfo}}  <el-divider direction="vertical"></el-divider>  存储总量： {{fileTotalInfo.fileSize.toFixed(2)}} {{fileTotalInfo.unit}} </span>
      </div></el-col>
      <el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
    </el-row>
<!--    功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-back"
          @click="handleBack"
        >后退</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-document-add"
          @click="handleAddFile"
        >上传文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-folder-add"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['file:flie:add']"
        >创建文件夹</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['file:flie:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="showZipFile"
        >上传文件夹</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
<!--      表格 -->
    <el-table v-loading="loading" :data="flieList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="文件名称" align="center" prop="originalFileName" >
<!--        简单的逻辑判断是否为文件夹 -->
<!--        如果是文件夹 设置按钮格式-->
        <template slot-scope="scope">
          <div v-if="showSwiper(scope.row)">
            <el-button
              size="mini"
              type="text"
              @click="handleLook(scope.row)"
            ><span>{{ scope.row.originalFileName}}</span></el-button>
          </div>
          <div v-else>
            <span>{{ scope.row.originalFileName}}</span>
          </div>
          <el-popover trigger="hover" placement="right">
            <p>记录id: {{ scope.row.id }}</p>
            <p>文件名称：{{ scope.row.originalFileName }}</p>
            <p>文件标签：{{ scope.row.labels }}</p>
            <p>记录类型: {{ scope.row.contentType }}</p>
            <p>文件大小: {{ scope.row.fileSize }}</p>
            <p>路径：{{ scope.row.pathFileName }}</p>
            <p>上传者: {{ scope.row.createBy }}</p>
            <p>上传时间: {{ scope.row.createTime }}</p>
            <p>修改人: {{ scope.row.updateBy }}</p>
            <p>修改时间: {{ scope.row.updateTime }}</p>
            <div slot="reference" class="name-wrapper">
              <el-button type="text">{{ scope.row.userName }}</el-button>
            </div>
          </el-popover>
        </template>

      </el-table-column>
      <el-table-column label="文件标签" align="center" prop="labels" >
        <template slot-scope="scope">
          <div v-for="(value) in scope.row.labels">
            <el-tag type="success">{{value}}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文件类型" align="center" prop="contentType" :formatter="contentTypeFormat" />
      <el-table-column label="文件大小" align="center" prop="fileSize" :formatter="calculateFileSize" />
<!--      <el-table-column label="文件路径" align="center" prop="pathFileName" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['file:flie:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['file:flie:remove']"
          >删除</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handlePreview(scope.row)"
              v-if="!showSwiper(scope.row)"
            >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownload(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 上传文件弹窗  -->
    <el-dialog id ="uploadFile" :title="title" :visible.sync="openFile" width="500px" append-to-body>

      <br>
      <el-form ref="form"  :rules="rules" label-width="80px">
        <el-form-item label="上传路径" >
          <treeselect v-model="fileObject.pcode" :props="defaultProps"  :options="materialOptions" :show-count="true" placeholder="请选择路径" />
        </el-form-item>
        <el-form-item label="素材">
          <el-upload
            ref="uploadImg"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            :action="uploadImg.url"
            :headers="uploadImg.headers"
            :file-list="uploadImg.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            :data="fileObject"
            :before-upload="uploadImgBeforeUpload">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="标记文本">
          <el-upload ref="uploadTxt"
                     :limit="1"
                     accept=".txt"
                     :action="uploadTxt.url"
                     :file-list="uploadTxtfileList"
                     :headers="uploadTxt.headers"
                     :on-progress="handleFileUploadProgress"
                     :on-success="handleFileSuccess"
                     :auto-upload="false"
                     :data="fileObject"
                     :before-upload="uploadTxtBeforeUpload">
            <el-button size="small" type="primary" icon="el-icon-upload">选择txt文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的.txt文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-left: 10px;" size="small" type="success" :loading="uploadImg.isUploading" @click="submitUpload" >上传到服务器</el-button>
        <el-button @click="cancel" class="mini">取 消</el-button>
      </div>


      </el-dialog>

    <!-- 上传文件夹  -->
    <el-dialog id="uploadZipFile" :title="title" :visible.sync="openZipFile" width="500px" append-to-body >

      <el-form ref="form"  :rules="rules" label-width="80px">
        <el-form-item label="上传路径" >
          <treeselect v-model="fileObject.pcode" :props="defaultProps"  :options="materialOptions" :show-count="true" placeholder="请选择路径" />
        </el-form-item>
<!--        代做识别压缩文件-->
        <el-form-item label="压缩包">
          <el-upload ref="uploadZip"
                     :limit="1"
                     accept=".zip"
                     :action="uploadTxt.url"
                     :file-list="uploadTxtfileList"
                     :headers="uploadTxt.headers"
                     :on-progress="handleFileUploadProgress"
                     :on-success="handleFileSuccess"
                     :auto-upload="false"
                     :data="fileObject"
                     >
            <el-button size="small" type="primary" icon="el-icon-upload">选择压缩文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的压缩t文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-left: 10px;" size="small" type="success" :loading="uploadImg.isUploading" @click="submitUpload" >上传到服务器</el-button>
        <el-button @click="cancel" class="mini">取 消</el-button>
      </div>


    </el-dialog>

    <!-- 添加或修改文件记录 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

<!--      <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>-->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="originalFileName">
          <el-input v-model="form.originalFileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="路径" prop="pcode">
          <treeselect v-model="fileObject.pcode" :props="defaultProps"  :options="materialOptions" :show-count="true" placeholder="请选择路径" />
        </el-form-item>
<!--        <el-form-item label="路径" prop="pcode" label-width="80px">-->
<!--          <treeselect v-model="form.pcode" :options="materialOptions" :show-count="true" placeholder="请选择归上传路径" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


<!--    <img src="https://img2.baidu.com/it/u=4033504488,813972093&fm=26&fmt=auto&gp=0.jpg">-->
    <!-- 图片显示 -->
    <el-dialog :title="title" :visible.sync="openShow" append-to-body >
      <div class="block" v-for="fit in fits" :key="fit" style="text-align: center;width: 100%;height: 100%;">
        <el-image
          style="width: 100%; height: 100%"
          :src="img_url"
          :fit="fit"></el-image>
        <canvas id="mycanvas" style="width: 100%; height: 100%"></canvas>
      </div>
    </el-dialog>
    <el-drawer
      title=""
      :visible.sync="drawer"
      :with-header="false">
      <span>我来啦!</span>
    </el-drawer>
    <!-- 视频显示 -->
    <el-dialog :title="title" :visible.sync="openShowVedio"  append-to-body>
      <div style="text-align: center;width: 100%;height: 100%;">
        <video    :preload="preload"
                  :poster="videoImg" :height="height" :width="width" align="center" :controls="controls"  :autoplay="autoplay">
          <source :src="video_url" type="video/mp4">
        </video>
      </div>
    </el-dialog>
  </div>
<!--  测试 图片 画图  -->



</template>

<script>
import {
  listFlie,
  getTableFlie,
  getFlie,
  delFlie,
  addFlie,
  updateFlie,
  exportFlie,
  getTotal,
  addFolder,
  downFile,
  getSelectTree,
  downloadFile,
  downloadFlie
} from "@/api/file/flie";
import {listTag_file} from "@/api/file/tag_file";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Flie",
  components: {
    Treeselect,
  },
  props: [],
  data() {
    return {
      //图片自适应
      fits:["fill"],
      // 画布信息
      startX: '',  //画画开始的X坐标
      startY: '',  //画画开始的Y坐标
      endX: '',    //画画结束的X坐标
      endY: '',    //画画结束的Y坐标
      isMouseDownInCanvas: '', //鼠标是否按下
      customcxt: '',      // cxt
      customRwidth: '',    //原图与展示图片的宽度比
      customRheight: '',   //原图与展示图片的高度比
      imgstyle: '',        //根据图片大小自适应样式
      canvasstyle: '',     //根据图片大小canvas自适应样式 居中显示
      canvasWidth: '',     //根据图片大小自适应canvas宽
      canvasHeight: '',    //根据图片大小自适应canvas高
      DivWidth: 1460,      //最大宽度
      DivHeight: 740,      //最大高度

      //目录树
      // 视频播放器组件
      videoSrc: '#',
      videoImg: '视频播放参数',
      playStatus: '',
      muteStatus: '',
      isMute: true,
      isPlay: false,
      width: '820', // 设置视频播放器的显示宽度（以像素为单位）
      height: '500', // 设置视频播放器的显示高度（以像素为单位）
      preload: 'auto', //  建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
      controls: true, // 确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
      autoplay: '',
      // 文件汇总细腻些
      fileTotalInfo: [],
      // 点击进去的目录链
      directoryList: [{pcode:-1,name:"/root",code:"-1"}],
      // 上传文件携带的额外信息 上传文件所在的文件夹位置 文件夹名称
      // 默认是根目录
      pcode: -1,
      // 文件上传组件
      // 上传参数
      uploadImg: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/flie/uploadFile",
        // 上传的文件列表
        fileList: [],
        filepath: null,
      },
      uploadTxt: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/flie/uploadFile",
        // 上传的文件列表
        fileList: [],
        filepath: null,
      },
      uploadZip: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/flie/uploadZipFile",
        // 上传的文件列表
        fileList: [],
        filepath: null,
      },
      uploadTxtAction: 'https://jsonplaceholder.typicode.com/posts/',
      uploadTxtfileList: [],
      uploadZipfileList: [],
      uploadZipAction: 'https://jsonplaceholder.typicode.com/posts/',
      fileObject:{pcode:'-1'},
      openFile: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件记录-2表格数据
      flieList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文件类型字典
      contentTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        originalFileName: null,
        contentType: null,
        pcode: -1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        originalFileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
      },
      // 预览模块
      openShow: false,
      openShowVedio: false,
      img_url: "https://img2.baidu.com/it/u=4033504488,813972093&fm=26&fmt=auto&gp=0.jpg",
      video_url: "/profile/upload/2021/07/14/963d4aa0-fca4-4eec-9d5f-b2a7729a5ced.mp4",
      // 创建文件夹
      openDir: false,
      //树形控件
      //级联选择器
      value: [],
      options: [ {
        id: 'a',
        label: 'a',
        children: [ {
          id: 'aa',
          label: 'aa',
        }, {
          id: 'ab',
          label: 'ab',
        } ],
      }, {
        id: 'b',
        label: 'b',
      }, {
        id: 'c',
        label: 'c',
      } ],
      materialOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      downloadObject: {
        fileName: '',
        delete: false,
      },
      queryTagParams: {
        pageNum: 1,
        pageSize: 10,
        fileCode: null,
        tagCategory: null,
        tagInfo: null,
      },
      // 标记文件信息表格数据
      tag_fileList: [],
      tag_total: null,
      tag_id: null,
      tag_name: null,
      ifFile: true,
      drawer: false,
      openZipFile: false,
    };
  },


  created() {
    this.handleSelectTree();
    this.getList();
    this.getDicts("base_file_type").then(response => {
      this.contentTypeOptions = response.data;
    });
  },
  methods: {
    showZipFile() {
      this.openZipFile = true;
      this.openFile = false;
      this.title = "上传文件夹"
    },
    // 处理文件大小
    calculateFileSize(row,column) {
      console.log(row)
      let file_size = row[column.property];
      let  count  = 0;
      if (file_size == 0){
        return  "";
      }
      while (file_size > 1024 && count++ < 5){
        file_size /= 1024;
      }
      file_size = file_size.toFixed(2);
      if (count == 0){
        file_size += "Byte";
      }else if (count == 1){
        file_size += " KB";
      }else if (count == 2){
        file_size += " GB";

      }else if (count == 3){
        file_size += " TB";
      }else {
        file_size += " PB";
      }
      return file_size;
    },
    /** 初始化目录树*/
    handleSelectTree(){
      getSelectTree().then(response => {
        this.materialOptions = response.data
        console.log(this.materialOptions);
      })
    },
    /** 点击链接 */
    handleLink(item){
      this.reset();
      const code = item.code;
      this.queryParams.pcode = code;
      const  list =  this.directoryList;
      let  i=0;
      for(;i<list.length;i++){
        if (list.length == 1){
          break;
        }
        if(item.code == list[i].code){
          for (let  j= i+1;j<list.length;j++){
            console.log(list.pop())
          }
        }

      }
      this.loading = true;
      listFlie(this.queryParams).then(response => {
        this.flieList = response.rows;
        this.total = response.total;
        this.pcode = item.pcode;
        this.loading = false;
      });

    },
// 文件提交处理
    submitUpload() {
      this.$refs.uploadImg.submit();
      this.$refs.uploadTxt.submit();
      this.$refs.uploadZip.submit();

    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploadImg.isUploading = true;
      this.uploadTxt.isUploading = true;
      this.uploadZip.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadImg.isUploading = false;
      this.uploadTxt.isUploading = false;
      this.uploadZip.isUploading = false;
      this.uploadImg.filePath = response.url;
      this.uploadTxt.filePath = response.url;
      this.uploadZip.filepath = response.url;
      this.msgSuccess(response.msg);
      this.getList();
      this.refresh();
      this.created();

    },
    uploadImgBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
    uploadZipBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('text/plain').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择.txt类型的文件')
      }
      return isRightSize && isAccept
    },
    uploadTxtBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('text/plain').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择.txt类型的文件')
      }
      return isRightSize && isAccept
    },
    // 对文件与文件夹的处理
    showSwiper (row) {
      if (row === ''){
        return false;
      }
      if(row.contentType.startsWith("folder")){
        return true;
      }else {
        return  false;
      }

    },
    /** 汇总信息 **/
    getTotals() {
      getTotal().then(response => {
        this.fileTotalInfo = response.data;
        console.log(this.fileTotalInfo);
        console.log(response);
      });
    },
    /**  */
    getList() {
      this.loading = true;
      listFlie(this.queryParams).then(response => {
        this.flieList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
      this.getTotals();


    },
    // 文件标签

    // 文件类型字典翻译
    contentTypeFormat(row, column) {
      return this.selectDictLabel(this.contentTypeOptions, row.contentType);
    },
    // 取消按钮
    cancel() {
      this.openFile = false;
      this.openDir = false;
      this.openShow = false;
      this.open = false;
      this.openZipFile = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        originalFileName: null,
        contentType: null,
        fileSize: null,
        pathFileName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        pcode: null,
        code:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 上传文件按钮操作 */
    handleAddFile() {
      this.fileObject.pcode = this.directoryList[this.directoryList.length-1].code;
      this.reset();
      this.uploadImg.fileList = [];
      this.uploadTxtfileList = [];
      this.openFile = true;
      this.title = "上传文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFlie(id).then(response => {
        // console.log(response.data);
        this.form = response.data;
        this.open = true;
        this.title = "修改文件记录";
      });
    },
    /** 新增文件夹按钮操作 */
    handleAdd() {
      this.fileObject.pcode = this.directoryList[this.directoryList.length-1].code;
      this.reset();
      this.open = true;
      this.title = "添加文件夹";
    },
    /** 后退按钮 */
    handleBack() {
      this.reset();
      const code = this.pcode;
      this.queryParams.pcode = code;
      if (this.directoryList.length != 1){
        this.directoryList.pop();
      }

      this.getList();
    },
    handleLook(row){
      this.directoryList.push({pcode: row.pcode,code:row.code,name:"/"+row.originalFileName})
      this.reset();
      const code = row.code;
      this.queryParams.pcode = code;
      this.getList();
    },
    /** 预览图片*/
    handlePreview(row){
      if(row.contentType.startsWith("video")){

        this.title = "视频预览";
        this.video_url  ="http://localhost:8080"+row.pathFileName;
        this.openShowVedio = true;
      }else if(
        row.contentType.startsWith("image")){
        this.img_url ="http://localhost:8080"+row.pathFileName;
        this.title = "预览图片";
        this.openShow = true;
        this.getTagList(row);

      }

    },
    /** 获取编辑图片的信息 **/

    /** 画矩形 提供点的坐标 颜色 粗细 绘制图片 画布 */

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let param= new URLSearchParams()
            param.append("p_code",this.fileObject.pcode)
            console.log("params"+this.form.pcode)
            updateFlie(this.form,param).then(response => {
              console.log("this.fileObject.pcode=="+this.fileObject.pcode)
              console.log("params"+param)
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.handleSelectTree();

            });
          } else {
            // this.form.pcode = this.directoryList[this.directoryList.length-1].code;
            this.form.contentType = "folder";
            this.form.pcode = this.fileObject.pcode;
            console.log("this.fileObject.pcode=="+this.fileObject.pcode)
            console.log(this.form.pcode)
            addFlie(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.handleSelectTree();
            });
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除文件记录-2编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFlie(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    onOpen() {},
    onClose() {
      this.$refs['fileForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    /** 确认按钮 **/
    handelConfirm() {
      this.$refs['fileForm'].validate(valid => {
        if (!valid) return
        this.close()
      })
    },

    // 文件下载处理
    handleDownload(row) {
      var fileId=row.id;
      console.log("row.contentType " + row.contentType)
      if (row.contentType == 'folder'){
        downloadFlie(fileId).then(response => {
          const aLink =document.createElement('a')
          const blob = new Blob([response], { type: 'application/zip' })
          let fileName = row.originalFileName +".zip"
          aLink.href = window.URL.createObjectURL(blob)
          aLink.setAttribute('download', fileName)
          document.body.appendChild(aLink)
          aLink.click()
          document.body.appendChild(aLink)
        }).catch(error => this.$message.error(error));
        return;
      }
      getTableFlie(fileId).then(response =>{
        this.tag_id = response.data.id;
        this.tag_name = response.data.originalFileName;
        // 标记文本下载
        downloadFlie(this.tag_id).then(response => {

          let blob = new Blob([response], {
            type: "application/octet-stream;charset=utf-8"
          });
          let fileName = this.tag_name;
          console.log(fileName);
          console.log("fileName");
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            //释放内存
            window.URL.revokeObjectURL(link.href);
          }
        })
          .catch(error => {
            console.log(error);
          });
      });
      // 素材的下载
      downloadFlie(fileId).then(response => {

        let blob;

        let fileName = row.originalFileName;

          blob = new Blob([response], {
            type: "application/vnd.ms-excel;charset=utf-8"
          });

        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          var link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          //释放内存
          window.URL.revokeObjectURL(link.href);
        }
      })
        .catch(error => {
          console.log(error);
        });
      console.log("tag_id "+ this.tag_id);


    },
    /** 查询标记文件信息列表 在图片上进行标记 */
    getTagList(row) {
      this.queryTagParams.fileCode=row.id;
      console.log(this.queryTagParams);
      console.log('id == id');
      listTag_file(this.queryTagParams).then(response => {
        this.tag_fileList = response.rows;
        this.tag_total = response.total;
        var canvas = document.getElementById("mycanvas")
        // 由于弹窗，确保已获取到
        var a = setInterval(() =>{
          // 重复获取
          canvas = document.getElementById("mycanvas")
          clearInterval(a);
          if(!canvas){
            return false
          } else {
            // 可以理解为一个画笔，可画路径、矩形、文字、图像
            var context = canvas.getContext('2d');
            var img = new Image();
            img.src = this.img_url;
            var tag = this.tag_fileList;
            // 加载图片
            console.log(this.tag_fileList);
            console.log("ff");img.onload = function(){
              if(img.complete){
                // 根据图像重新设定了canvas的长宽
                canvas.setAttribute("width",img.width== null?1000:img.width);
                canvas.setAttribute("height",img.height==null?1000:img.height);
                // 绘制图片
                context.drawImage(img,0,0,img.width,img.height);

                // 绘制矩形
                var i ;
                for(i = 0 ;i<tag.length;i++){
                    var points = tag[i].tagInfo.split(" ");
                    //绘制矩形
                  console.log(points);

                    context.strokeStyle = '#' + Math.random().toString(16).substr(2, 6).toUpperCase();
                    context.lineWidth = 2;
                    context.strokeRect(points[0], points[1], Math.abs(points[2]-points[0]), Math.abs(points[3]-points[1]));
                    context.font = "26px Arial bolder";
                    context.fillStyle = 'red';
                    context.fillText(tag[i].tagCategory,points[0],points[3])

                }

                console.log("ddd")
              }
            }


          }
        },1);
      });
    },
  },
  /* 下载文件的公共方法，参数就传blob文件流*/
  handleExport(data) {
    // 动态创建iframe下载文件
    let fileName = "1111";
    if (!data) {
      return;
    }
    let blob = new Blob([data], { type: "application/octet-stream" });
    if ("download" in document.createElement("a")) {
      // 不是IE浏览器
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); // 下载完成移除元素
      window.URL.revokeObjectURL(url); // 释放掉blob对象
    } else {
      // IE 10+
      window.navigator.msSaveBlob(blob, fileName);
    }
  },
  // 处理文件大小
  handleFileSize(file_size) {
      let  count  = 0;
      while (file_size > 1024 && count++ < 6){
          file_size /= 1024;
      }
      file_size = file_size.toFixed(2);
    if (count == 1){
      file_size += "Byte";
    }else if (count == 2){
      file_size += " KB";
    }else if (count == 3){
      file_size += " GB";

    }else if (count == 4){
      file_size += " TB";
    }else {
      file_size += " PB";
    }
    return file_size;
  },
  //鼠标按下时执行
  mousedown(e) {
    this.isMouseDownInCanvas = true;
    // 鼠标按下时开始位置与结束位置相同
    // 防止鼠标在画完矩形后 点击图画形成第二个图形
    this.endX = e.offsetX;
    this.endY = e.offsetY;
    this.startX = e.offsetX;
    this.startY = e.offsetY;
    this.mousemove(e)

  },
  //鼠标移动式时执行
  mousemove(e) {
    if (this.isMouseDownInCanvas) { // 当鼠标有按下操作时执行

      this.endX = e.offsetX;
      this.endY = e.offsetY;
      let wwidth = this.endX - this.startX;
      let wheigth = this.endY - this.startY;

      // 清除指定区域的所有像素
      this.customcxt.clearRect(0, 0, this.DivWidth, this.DivHeight);
      this.customcxt.strokeStyle = " #00ff00"; //矩形框颜色
      this.customcxt.lineWidth = "2";  //矩形框宽度
      this.customcxt.strokeRect(this.startX, this.startY, wwidth, wheigth);  //绘制矩形

    }
  },
  //鼠标松开时执行
  mouseup(e) {
    this.isMouseDownInCanvas = false;
  },

  Mouseleave(e) {
    this.isMouseDownInCanvas = false
  },
};
</script>
